from paho.mqtt import publish

from utilsapp.mysql_con import db_operation, db_connect


def index(settings, data):
    topic = data.get("topic")
    msg = data.get("payload")
    port = topic.split("/")[1]
    address = topic.split("/")[2]
    alarm_type = topic.split("/")[3]
    if alarm_type == "sthred":
        title = "固定阈值告警"
    elif alarm_type == "thred":
        title = "动态阈值告警"
    elif alarm_type == "trend":
        title = "趋势异常告警"
    else:
        title = "PHMAI告警"
    s1 = f'''
            insert into warn(title,content,warn_source,warn_type,warn_level,device_id,sensor_id,group_id,company_id,factory_id
            ,zone_id,type_id,create_time,is_show)
            select '{title}' as title,CONCAT_WS(':',s.sensor_name,t.trouble,t.description) as content,t.namecode as warn_source
            ,t.typecode as warn_type,{msg.get("level")} as warn_level,s.device_id as device_id,s.id as sensor_id,s.group_id as group_id,
            s.company_id as company_id,s.factory_id as factory_id,s.zone_id as zone_id,d.type_id,'{msg.get("time")}' as create_time,
            1 as is_show from sensor s left join device d on s.device_id=d.id left join trouble t on t.typecode="BF01.001"
             where s.address='{address}' and s.port='{port}'
            '''
    db_operation(s1)
    s2 = "select * from warn where notice is null order by create_time desc limit 1"
    # 然后发出的告警的mqtt消息供前端使用
    res = db_connect(s2)
    publish.single("c_" + topic, str(res.get("data")), qos=0, hostname=settings["mqtt-url"],
                   port=settings["mqtt-port"],
                   auth={'username': settings["mqtt-username"], 'password': settings["mqtt-password"]})
    return
